package puppy.graph;
import java.awt.Dimension;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;

import java.util.regex.Pattern;

import javax.swing.JFrame;



import puppy.query.QueryNGramExtractor;

import util.io.FileInput;

import util.string.URLCleaner;

import edu.uci.ics.jung.algorithms.layout.CircleLayout;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.UndirectedSparseGraph;
import edu.uci.ics.jung.visualization.BasicVisualizationServer;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;


import fileloaders.mallet.MalletTopicsProbs;
import fileloaders.parsers.InLineParser;
public class CreateGraphSimple {

	private static final Integer EDGE_THRESHOLD = 3;
	private static final Integer NODE_THRESHOLD = 3;
	
	
	private static final Integer EDGE_THRESHOLD_KIDS = 2;
	private static final Integer NODE_THRESHOLD_KID = 3;
	
	float threshold_d=0.01f;
	float threshold_w=0.05f;
	
	
	/**
	 * @param args
	 */
	public int n_nodes = 0;
	public int n_edges = 0;

	// Generate
	// id_url, id_tag, url,tag,freq_tag,freq_url, freq_ut,type
	
	
	//http://5.ua/	tv_news	adults	11953	10	3	5.ua

	
	public UndirectedSparseGraph<DeliciousNode, DeliciousEdge> graph= null;
	
	private Pattern tab = Pattern.compile("\t");
	public Hashtable<String,String> urls_simplified = new  Hashtable<String,String> ();
	
	public QueryNGramExtractor query_phraser = new QueryNGramExtractor();
	public Hashtable<String, DeliciousNode> nodes = new Hashtable<String, DeliciousNode>();

	AgeAggregator agg= null;

	/**
	 * Topic fields
	 * 
	 * 
	 * 
	 */
	//TODO change this
	public Hashtable<String,Hashtable<Short,Float>> w_topics= new  Hashtable<String,Hashtable<Short,Float>>();
	
	public Hashtable<String,Hashtable<Short,Float>> topics_docs= new  Hashtable<String,Hashtable<Short,Float>>();
	public Hashtable<String,Float> z_probs = new Hashtable<String,Float> ();
	
	public void initTopics(String w_p, String d_p, String z_path){
		
		if(w_p!=null && d_p!=null){
		MalletTopicsProbs.loadTopicGivenDoc(d_p, topics_docs);
		MalletTopicsProbs.loadTopicGivenWord(w_p, w_topics);
		}
		
		
		MalletTopicsProbs.loadTopicProbs(z_path, z_probs);
		
	}
	
	private boolean createTopicNodes= false;
	public CreateGraphSimple(AgeAggregator agg, String w_p, String d_p,String z_p){
		
		this.agg=agg;
		initTopics(w_p,d_p,z_p);
		if(w_p!=null && d_p!=null && z_p !=null)createTopicNodes=true;
	}
	
	public void initGraph(String path) {

		FileInput in = new FileInput(path);
		graph = new UndirectedSparseGraph<DeliciousNode, DeliciousEdge>();
		
		
		String line = in.readString();
		
		int j =0;
		while (line != null) {
		//	System.out.println("Adding " + line);
			dumpLineIntoGraphDirected(graph, line);
			line = in.readString();
			j++;
	//	if(j==5) return;
		}
	}


	public void aggreageteValueInHash(Hashtable<String,Integer>h, String key, int value){
		
		if(h.containsKey(key)){
			
			h.put(key, h.get(key)+ value);
			
		}else{
			
			h.put(key, value);
			
		}
		
	}
	
	private void dumpLineIntoGraphDirected(
			UndirectedSparseGraph<DeliciousNode, DeliciousEdge> graph,
			String line) {

		String[] fields =  tab.split(line);

		//System.out.println(line);
		line =null;
		Hashtable<String, Object[]> f = InLineParser.parseGraphEnrichedLineAgg(fields,agg);
		
		
		String[] url_tag=  (String[]) f.get("keys");

		
		f.remove("keys");
		Enumeration<String> keys = f.keys();
		
		DeliciousNode url=null;
		DeliciousNode tag=null;
	
		if(nodes.containsKey(url_tag[0])){
			url = nodes.get(url_tag[0]);
			
		}
		
		if(nodes.containsKey(url_tag[1])){
			tag= nodes.get(url_tag[1]);
			
		}
		
		DeliciousEdge edge =null;
		Float freq_ut=0f;
		
		
		
		String age= "kids";
		Float []freqs  = (Float[]) f.get(age);
		
		
		
		Float freq_tag =freqs[0]; 
		Float freq_url=freqs[1];
		freq_ut=freqs[2];
		
		Float adult_freq_tag=freqs[3]; 
		Float adult_freq_url=freqs[4];
		
		if(freq_tag==0) return;
				
		/**
		 * Verify why this is neccesary
		 */
		url=null;
		tag=null;
		
		/**
		 * end of verify why this is neccesary
		 * 
		 */
		
		/*
		 * Adding url node
		 */
		
		
		if(tag==null){
			
			tag = new DeliciousNode();
			tag.setName(url_tag[1]);
			tag.setType(false);
	    	tag.setProb_adults(adult_freq_tag);
	    	nodes.put(url_tag[1], tag);
	    	//add node to trie dictionary
			//if(name.contains("_")){
			//query_phraser.addItem(name);
			//}
			
		}
		
		
		if(url==null){
			url = new DeliciousNode();
			url.setName(url_tag[0]);
			url.setType(true);
			
			url.setProb_adults(adult_freq_url);
			
			nodes.put(url_tag[0], url);
			
			
			 String simple =URLCleaner.simplifyURL(url_tag[0],1);
				if(simple.equals("swl.nu"))System.out.println("si lo encontro: swl.nu" );
				 urls_simplified.put(simple,url_tag[0]);
		}
		url.setProb(freq_url);
			
		
		tag.setProb(freq_tag);
					
		//	aggreageteValueInHash(urls_totals,age, freq_url);	
		//create edge
		
		edge = new DeliciousEdge();
		edge.tag=tag;
		edge.url=url;
		edge.setProb(freq_ut);
		
	
	
	if (tag != null && url != null) {
		
		graph.addVertex(tag);
		graph.addVertex(url);
		graph.addEdge(edge, url, tag);
		
		
		
		if(createTopicNodes){
		createTopicLinks(tag, threshold_d, threshold_w);
		createTopicLinks(url, threshold_d, threshold_w);
		}
		
		
	}
	
	
		
		
		
		//while(keys.hasMoreElements()){
			
			//String age = keys.nextElement();
			//url, tag, freq_tag, freq_url, freq_ut, type, f_t, f_u,domain 
			
			
			//if(!agg.isAgeValid(age) ){
				
				//continue;
				
		//	}
	//	}
			
	
	}
	
	public void createTopicLinks(DeliciousNode a, float threshold_d,  float threshold_w){
	
		
		if(!a.isTag()){
			
			 String simple =URLCleaner.simplifyURL(a.getName(),1);
			 Hashtable<Short, Float> topics=null;
			
				 topics = topics_docs.get(simple);
		
			Enumeration<Short> keys = topics.keys();
			
			while(keys.hasMoreElements()){
				
				Short topic = keys.nextElement();
				Float z_doc= topics.get(topic);
				
				Float prob_topic = z_probs.get("t-"+topic);
				if(prob_topic>threshold_d){
					
					//create adge url --> z 
					DeliciousNode z = new DeliciousNode();
					String name ="t-"+ String.valueOf(topic);
				//	System.out.println("Adding link:" + name + "\t"+ a.getName()  + "\t"+ prob);
					z.setName("t-" + String.valueOf(topic));
					z.setProb(prob_topic);
					
					if(!nodes.containsKey(z)){
						nodes.put(name, z);	
					}
					
					graph.addVertex(z);
					DeliciousEdge edge= new DeliciousEdge();
					edge.url= a;
					edge.tag=z;
					edge.setProb(prob_topic);
					graph.addEdge(edge, a, z);
					
					
			}
		  }
		}
		
		else{
		//	System.out.println(a.getName());
			Hashtable<Short, Float> topics = w_topics.get(a.getName());
			Enumeration<Short> keys = topics.keys();
			String name = a.getName();
			while(keys.hasMoreElements()){
				
				Short topic = keys.nextElement();
				
				Float z_prob = z_probs.get(new String("t-"+ topic));
				Float z_tag= topics.get(topic);
				if(z_prob>threshold_w){
					
					//create adge url --> z 
					DeliciousNode z = new DeliciousNode();
					//System.out.println("adding link " + a.getName() + "\t"+ name);
					z.setName("t-" + String.valueOf(topic));
					
					z.setProb(z_prob);
					
					if(!nodes.containsKey(z)){
						nodes.put(name, z);	
					}
					
					graph.addVertex(z);
					DeliciousEdge edge= new DeliciousEdge();
					edge.url= z;
					edge.setProb(z_tag);
					edge.tag=a;
					graph.addEdge(edge, a, z);
					
					
			}
		  }
			
			
			
		}
		
		
		
	}
	
	
	public static void main(String args[]){
		

		DeliciousNode node = new DeliciousNode();
		UndirectedSparseGraph<DeliciousNode,DeliciousEdge> graph= new UndirectedSparseGraph<DeliciousNode,DeliciousEdge>();
		
		node.setName("A");
		
		DeliciousNode node1 = new DeliciousNode();
		
		node1.setName("B");
		
		
		DeliciousNode node2 = new DeliciousNode();
		node2.setName("C");
		
		
		DeliciousNode node2b = new DeliciousNode();
		node2b.setName("C");
		
		DeliciousNode node4 = new DeliciousNode();
		node4.setName("D");
		
		
		DeliciousNode node5 = new DeliciousNode();
		node5.setName("E");
		
		
		DeliciousNode node6 = new DeliciousNode();
		node6.setName("F");
		DeliciousEdge edge =  new DeliciousEdge();
	
		DeliciousEdge edge2 =  new DeliciousEdge();
		DeliciousEdge edge3 =  new DeliciousEdge();
		DeliciousEdge edge4 =  new DeliciousEdge();
		DeliciousEdge edge5 =  new DeliciousEdge();
		DeliciousEdge edge6 =  new DeliciousEdge();
		DeliciousEdge edge7 =  new DeliciousEdge();
		
		
		
		graph.addEdge(edge, node,node1);
		graph.addEdge(edge5, node1,node2);
		
		
		System.out.println(edge5..geIncidentCount(edge5));
		graph.addEdge(edge2, node2,node4);
		
		graph.addEdge(edge7, node2b,node4);
		
		
		graph.addEdge(edge3, node4,node5);
		graph.addEdge(edge4, node6,node4);
		graph.addEdge(edge6, node1,node6);
	
		
		
		HashSet<DeliciousNode> set = new HashSet<DeliciousNode>();
		set.add(node);
		
		
		HashSet<String> set1 = new HashSet<String>();
		set1.add("a");
		
		GraphExtractor extractor= new GraphExtractor(2,set);
		Graph<DeliciousNode, DeliciousEdge> temp = extractor.extractGraph(graph);
		
		Layout<Integer, String> layout = new CircleLayout(graph);
	    layout.setSize(new Dimension(300,300)); // sets the initial size of the space
	     // The BasicVisualizationServer<V,E> is parameterized by the edge types
	     BasicVisualizationServer<Integer,String> vv =
	              new BasicVisualizationServer<Integer,String>(layout);
	     vv.setPreferredSize(new Dimension(350,350)); //Sets the viewing area size
	        vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());

	    
	     
	     JFrame frame = new JFrame("Simple Graph View");
	     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	     frame.getContentPane().add(vv);
	     frame.pack();
	     frame.setVisible(true);
		
		
		
		
		
	}

	
	
	public void createGraph1(){
		

	
	
		
		
	}

	

}